package com.wjj.sixinone.interceptor;



import com.alibaba.fastjson2.JSON;
import com.wjj.sixinone.common.enums.ApiTypeConst;
import com.wjj.sixinone.common.enums.ExceptionEnum;
import com.wjj.sixinone.common.enums.UserEnum;
import com.wjj.sixinone.common.exception.GlobalException;
import com.wjj.sixinone.common.pojo.entity.User;
import com.wjj.sixinone.common.util.AuthContextUtil;
import com.wjj.sixinone.common.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求方式
        String method = request.getMethod();
        if("OPTIONS".equals(method)) {      // 如果是跨域预检请求，直接放行
            return true ;
        }
        String token = request.getHeader("Authorization");

        if (token == null || !availableToken(token)) {
            throw new GlobalException(ExceptionEnum.INVALID_TOKEN);
        }

        // 从令牌中提取用户角色
        String userRole = jwtUtil.getUserInfoFromToken(token, UserEnum.USER_ROLE.getKey());

        // 验证用户角色是否存在
        if (userRole == null) {
            throw new GlobalException(ExceptionEnum.INVALID_TOKEN);
        }

        String path=request.getServletPath();

        if(path.contains(ApiTypeConst.API_ADMIN)&&!userRole.equals(UserEnum.ROLE_ADMIN.getKey())){
            throw new GlobalException(ExceptionEnum.INVALID_AUTH_ERROR);
        }

        if(request.getServletPath().contains(ApiTypeConst.API_USER)&&(!userRole.equals(UserEnum.ROLE_USER.getKey())&&!userRole.equals(UserEnum.ROLE_ADMIN.getKey()))){
            throw new GlobalException(ExceptionEnum.INVALID_AUTH_ERROR);
        }

        // 从Redis中获取用户信息，基于令牌
        String userKey=UserEnum.USER_ID.getKey()+token;
        String userJson = redisTemplate.opsForValue().get(userKey);
        if (userJson == null) {
            throw new GlobalException(ExceptionEnum.UNAUTHORIZED);
        }
        User user = com.alibaba.fastjson.JSON.parseObject(userJson, User.class);
        AuthContextUtil.set(user);
        redisTemplate.opsForValue().set(userKey, JSON.toJSONString(user),7,TimeUnit.DAYS);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }

    private boolean availableToken(String token) {
        return jwtUtil.checkToken(token);
    }

}
